import 'package:applications/module/home/dao/application_dao.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as path;
import 'package:sqflite/sqflite.dart';

class LocalDb {
  Database? _database;

  LocalDb._();

  static LocalDb instance = LocalDb._();

  late ApplicationDao _applicationDao;

  ApplicationDao get applicationDao => _applicationDao;

  Database get db => _database!;

  Future<void> initDb({String name = "applications.db"}) async {
    if (_database != null) return;
    String databasesPath = await getDatabasesPath();
    String dbPath = path.join(databasesPath, name);

    _database = await openDatabase(
      dbPath,
      version: 2,
      onOpen: (db) {},
      onCreate: (Database db, int version) async {
        debugPrint("当前版本:$version");
        await ApplicationDao.create(db);
      },
      onUpgrade: (Database db, int oldVersion, int newVersion) async {
        debugPrint("旧的版本:$oldVersion");
        await ApplicationDao.onUpgrade(db, oldVersion);
      },
    );

    _applicationDao = ApplicationDao(_database!);
    debugPrint('初始化数据库....');
    debugPrint(dbPath);
  }

  Future<void> closeDb() async {
    await _database?.close();
    _database = null;
  }
}
